import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // 动态设置网页的标题
  // document.title = '人力资源管理系统-' + to.meta.title
  document.title = getPageTitle(to.meta.title)
  console.log(to.path, '去哪里')
  console.log(from.path, '从哪里来')
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    // 已经登录
    if (to.path === '/login') {
      // 有token，还去登录 ---> 直接去主页
      console.log('有token,还去登录 ---> 直接去主页')
      next('/')
      NProgress.done()
    } else {
      if (!store.state.user.userInfo.userId) {
        await store.dispatch('user/setUserInfo')
      }
      next()
    }
  } else {
    // 没有登录
    // 是否白名单,不需要token,/login || /404
    // whiteList.include() // 判断传入的内容在不在数组中,返回值是布尔值
    if (whiteList.includes(to.path)) {
      console.log('拥有白名单,直接放行')
      next()
    } else {
      console.log('没有登录,没有白名单,跳转登录页')

      next('/login')
      NProgress.done()
    }
  }
  console.log(token, '路由跳转', from.path, '----->', to.path)
})
router.afterEach(() => {
  NProgress.done()
})
